// pages/body-detail/body-detail.js
const app = getApp();
const util = require('../../utils/util.js');
const chartUtil = require('../../utils/chartUtil.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    body: null,
    bodyList: [],
    animation: null,
    showModal: false,
    bodyText: '',
    currentUnit: '',
    // 保存的值
    saveValue: 0,
    bodyItems: getApp().globalData.bodyItems,
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.bodyText) {
      this.setData({
        bodyText: options.bodyText
      });
    }
    if (options.attribute) {
      this.setData({
        attribute: options.attribute
      });
    }
    if (options.bodyUnit) {
      this.setData({
        bodyUnit: options.bodyUnit
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    this.loadBody().then(
      res => {
        // 加载线形图
        chartUtil.buildLine(this.getChartData());
      },
      res => {}
    );

  },

  // 获取图表所需数据
  getChartData: function () {
    console.log('获取图表所需数据');
    var tempData = this.data.body[this.data.attribute].data ? this.data.body[this.data.attribute].data : [];
    console.log(tempData);
    var categories = [];
    var data = [];

    for (var i = 0; i < tempData.length; i++) {
      categories.push(tempData[i].time);
      data.push(tempData[i].value);
    }

    return {
      categories: categories,
      data: data
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 选项卡事件
  menuTap: function(e) {
    var that = this;
    // 获取到绑定的数据
    var current = e.currentTarget.dataset.current;
    var unit = e.currentTarget.dataset.unit;
    var attribute = e.currentTarget.dataset.attribute;
    

    //改变menuTapCurrent的值为当前选中的menu所绑定的数据
    var list = this.data.body[attribute].data;
    that.setData({
      bodyText: current,
      bodyUnit: unit,
      attribute: attribute,
      bodyList: list
    });
    
    // 加载线形图
    chartUtil.buildLine(this.getChartData());
  },
  // 滚动事件
  onPageScroll: function(e) {
    var that = this;
    // 淡出动画
    that.fadeOut();

    // 指定时间后 显示底部按钮
    setTimeout(function() {
      // 淡入动画
      that.fadeIn();
    }, 1000);
  },
  /**
   * 淡入动画
   */
  fadeIn: function() {
    //创建动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0,
      transformOrigin: "50% 50%",
    });
    // animation.opacity(1).step();
    animation.height('80rpx').step();
    //导出动画数据传递给组件的animation属性。
    this.setData({
      animation: animation.export(),
    });
  },
  /**
   * 淡出动画
   */
  fadeOut: function() {
    //创建动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0,
      transformOrigin: "50% 50%",
    });
    // animation.opacity(0).step();
    animation.height('0rpx').step();
    //导出动画数据传递给组件的animation属性。
    this.setData({
      animation: animation.export(),
    });
  },

  // 显示模态框
  showModal: function() {
    this.setData({
      showModal: true,
      saveValue: 0,
    });
  },

  // 隐藏模态框
  hideModal: function() {
    this.setData({
      showModal: false,
      saveValue: 0,
    });
  },

  // 设置数据
  setSaveValue: function(e) {
    // console.log(e.detail.value);
    this.setData({
      saveValue: e.detail.value
    });
  },

  loadBody: function () {
    return new Promise((resolve, reject) => {
      var that = this;
      const fileManage = wx.getFileSystemManager();

      fileManage.readFile({
        filePath: app.globalData.bodyDataPath,
        encoding: 'utf8',
        success: res => {
          console.log("文件内容读取成功：");
          console.log(res);
          var body = JSON.parse(res.data);
          var attribute = that.data.attribute;
          that.setData({
            body: body,
            bodyList: body[attribute].data,
            currentUnit: body[attribute].unit, 
          });
          resolve(true);
        },
        fail: res => {
          console.log("文件内容读取失败");
          console.log(res);
          reject(false);
        }
      });
    });
  },

  // 今日是否存在数据
  currentDateExistsData: function () {
    var that = this;
    var bodyText = that.data.bodyText;
    var attribute = that.data.attribute;
    var body = that.data.body;
    var tempData = body[attribute].data;
    for (var i = 0; i < tempData.length; i++) {
      if (tempData[i].time == util.formatCurrentDate()) {
        return true;
      }
    }

    return false;
  },

  // 保存数据
  ok: function(e) {
    var that = this;
    var bodyText = that.data.bodyText;
    var attribute = that.data.attribute;
    var value = parseFloat(that.data.saveValue);
    var body = that.data.body;
    console.log(body);
    if (value == '') {
      wx.showToast({
        title: '请输入数据',
        icon: 'none'
      });
      return;
    }

    // 校验今日是否存在数据, 存在则覆盖，否则添加
    var isExists = that.currentDateExistsData();
    if (isExists) {
      body[attribute].data[0].value = value;
    } else {
      var item = { time: util.formatCurrentDate(), value: value };
      body[attribute].data.unshift(item);
    }

    console.log("body after:");
    console.log(body);

    // 写入body数据
    var fileManage = wx.getFileSystemManager();
    fileManage.writeFile({
      filePath: app.globalData.bodyDataPath,
      data: JSON.stringify(body),
      encoding: 'utf8',
      success: res => {
        console.log("记录成功");
        // 更新数据
        that.setData({
          body: body,
          bodyList: body[attribute].data,
        });
        // 加载线形图
        chartUtil.buildLine(that.getChartData());
      },
      fail: res => { 
        console.log("记录失败:");
        console.log(res);
      },
      complete: res => {
        console.log("记录完成");
        that.hideModal();
      }
    });
    
  },
})